package com.example.myblogserver.controller.admin;

import com.example.myblogserver.common.context.BaseContext;
import com.example.myblogserver.common.properties.JwtProperties;
import com.example.myblogserver.common.result.Result;
import com.example.myblogserver.common.utils.JwtUtil;
import com.example.myblogserver.dto.AdminLoginDTO;
import com.example.myblogserver.model.UsersAccount;
import com.example.myblogserver.service.AdminService;
import com.example.myblogserver.vo.AdminLoginVO;
import com.example.myblogserver.vo.UserInfoVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Slf4j
@Api(tags = "员工相关接口")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 登录
     *
     * @param adminLoginDTO
     * @return
     */
    @PostMapping("/auth/login")
    @ApiOperation(value = "管理员登录")
    public Result<AdminLoginVO> login(@RequestBody AdminLoginDTO adminLoginDTO) {
        log.info("管理员登录：{}", adminLoginDTO);

        UsersAccount usersAccount = adminService.login(adminLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("UserEmail", usersAccount.getUserEmail());
        claims.put("UserId", usersAccount.getUserId());
        //生成jwt令牌，参数1：密钥，参数2：令牌有效期，参数3：自定义信息
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        //将登录者的email放到当前线程中
        BaseContext.setCurrentUserEmail(usersAccount.getUserEmail());
        //封装返回结果
        AdminLoginVO adminLoginVO = AdminLoginVO.builder()
                .userEmail(usersAccount.getUserEmail())
                .token(token)
                .build();

        return Result.success(adminLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/auth/logout")
    @ApiOperation("管理员退出")
    public Result<?> logout() {
        return Result.success();
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    @GetMapping("/user/getInfo")
    @ApiOperation("获取当前登录用户信息")
    public Result<UserInfoVO> getInfo() {
        log.info("获取当前登录用户信息");
        log.info("当前登录用户email：{}", BaseContext.getCurrentUserEmail());
        UserInfoVO userInfoVO = UserInfoVO.builder()
                .userEmail(BaseContext.getCurrentUserEmail())
                .nickName("七安")
                .build();
        return Result.success(userInfoVO);
    }


}
